package com.example.springboot.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.springboot.common.ResultCode;
import com.example.springboot.common.config.JwtTokenUtils;
import com.example.springboot.dao.ComboDao;
import com.example.springboot.entity.Account;
import com.example.springboot.entity.Combo;
import com.example.springboot.entity.User;
import com.example.springboot.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ComboService {
    @Resource
    ComboDao comboDao;
    public List<Combo> GetAll() {
        return comboDao.selectAll();
    }


    public Combo findById(Integer id) {

        return comboDao.findById(id);
    }

    public Combo comboRegister(Combo combo) {

        String userName = combo.getUserName();
//     1.先校验用户名是不是为空： 如果用户名，为空，抛出异常
        if (ObjectUtil.isEmpty(userName)){
            throw new CustomException(ResultCode.USERNAME_ISNULL);
        }
//     2.校验用户名的唯一性：
        Combo dbCombo = comboDao.findByName(userName);
        if (ObjectUtil.isNotEmpty(dbCombo)) {
            throw new CustomException(ResultCode.USER_EXIST_ERROR);
        }

        comboDao.insertSelective(combo);
        return combo;
    }

    public void delete(Integer id) {
        comboDao.deleteByPrimaryKey(id);
    }



    public Combo comboEdit(Combo combo) {

        String userName = combo.getUserName();
//     校验用户名是不是为空： 如果用户名，为空，抛出异常
        if (ObjectUtil.isEmpty(userName)){
            throw new CustomException(ResultCode.USERNAME_ISNULL);
        }
        comboDao.updateByPrimaryKeySelective(combo);

        return combo;
    }

    // 分页查询和模糊查询的方法
    //PageInfo 里面装的是分页后分装的数据，返回值也要用PageInfo.of()包裹
    public PageInfo<Combo> findPage(Combo search, Integer pageNum, Integer pageSize) {
        //获取当前用户，判断当前用户是否处于登录状态
        Account user = JwtTokenUtils.getCurrentUser();//获取当前用户
        if (ObjectUtil.isEmpty(user)) {
            throw new CustomException(ResultCode.USER_NOT_LOGIN);
        }
        // 开启分页（开启分页后一定是操作数据库）
        PageHelper.startPage(pageNum, pageSize);
        List<Combo> all = findByCondition(search);

        return PageInfo.of(all);
    }

    // 根据条件查询的方法
    public List<Combo> findByCondition(Combo search) {
        return comboDao.findBySearch(search);
    }

}
